package com.och.mrcp.handler;

import com.och.mrcp.core.rtp.session.RtpSessionManager;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.ChannelHandler.Sharable;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * RTP包处理器
 * 处理接收到的RTP数据包
 */
@Slf4j
@Component
@RequiredArgsConstructor
@Sharable
public class RtpPacketHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    
    private final RtpSessionManager sessionManager;
    
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
        try {
            InetSocketAddress sender = packet.sender();
            ByteBuf content = packet.content();
            
            // 读取包数据
            byte[] packetData = new byte[content.readableBytes()];
            content.readBytes(packetData);
            
            log.info("★★★ RECEIVED RTP PACKET ★★★ from {}:{}, size: {} bytes, local: {}", 
                    sender.getAddress().getHostAddress(), sender.getPort(), packetData.length,
                    ctx.channel().localAddress());
            
            // 打印数据包的前16字节用于调试
            if (packetData.length > 0) {
                StringBuilder hex = new StringBuilder();
                for (int i = 0; i < Math.min(16, packetData.length); i++) {
                    hex.append(String.format("%02X ", packetData[i]));
                }
                log.info("RTP packet hex (first 16 bytes): {}", hex.toString());
            }
            
            // 转发给会话管理器处理
            sessionManager.handleRtpPacket(sender, packetData);
            
        } catch (Exception e) {
            log.error("Error processing RTP packet from {}: {}", packet.sender(), e.getMessage(), e);
        }
    }
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("RTP channel active: {}", ctx.channel().localAddress());
        super.channelActive(ctx);
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("RTP channel inactive: {}", ctx.channel().localAddress());
        super.channelInactive(ctx);
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("RTP channel exception: {}", cause.getMessage(), cause);
        ctx.close();
    }
}
